package com.vgemv.jsutilitysdk.JsNetworkManager;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;


import com.vgemv.jsutilitysdk.JsJsonManager.JsJsonManager;
import com.vgemv.jsutilitysdk.Request.JsRequestManager.JsRequestManager;

import java.lang.reflect.Method;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Response;

public class JsIpManager {

    public static JsIpInfoModel getCurrentIpInfo(Context context) {
        JsIpInfoModel ipInfoModel = new JsIpInfoModel();
        String ip = getIpAddressViaSina();
        if(ip == null || ip.length() == 0) {
            ip = getIpAddressViaNative(context);
        }
        ipInfoModel.ip = ip;

        String webServiceProviderName = getNetworkOperatorName(context);
        ipInfoModel.webServiceProviderName = webServiceProviderName;
        return ipInfoModel;
    }

    /**
     * 调用新浪的接口获取ip地址.
     * @return
     */
    private static String getIpAddressViaSina() {
        String urlString = "http://pv.sohu.com/cityjson?ie=utf-8";
        String str_result = null;
        String str_ip = null;
        try {
            Response response = JsRequestManager.sharedInstance().getRequestSync(urlString,null);
            String str_response = response.body().string();
            String str_stdPrefix = "var returnCitySN = ";

            if(str_response.contains(str_stdPrefix)) {
                str_response =str_response.replace(str_stdPrefix,"");
                str_response = str_response.substring(0,str_response.length()-1);
                Map<String, String> map = JsJsonManager.defaultGson().fromJson(str_response, HashMap.class);
                str_ip = map.get("cip");
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return str_ip;
    }

    private static String getIpAddressViaNative(Context context) {
        String ip = null;
        //为什么要context才能获得服务对象?

        ConnectivityManager conMann = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mobileNetworkInfo = conMann.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        NetworkInfo wifiNetworkInfo = conMann.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

        if (mobileNetworkInfo.isConnected()) {
                ip = getLocalIpAddress();
            System.out.println("本地ip-----"+ip);
        }else if(wifiNetworkInfo.isConnected()){
                WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                int ipAddress = wifiInfo.getIpAddress();
                ip = intToIp(ipAddress);
            System.out.println("wifi_ip地址为------"+ip);
        }
        return ip;
    }


    /**
     * 当前inetAddress是否是ipv4的地址.
     * @return
     */
    public static boolean isIpAddressV4(InetAddress inetAddress) {
        if(inetAddress instanceof Inet4Address) {
            return true;
        }
        return false;

    }


    public static String getLocalIpAddress() {
        try {
            String ipv4;
            ArrayList<NetworkInterface> nilist = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface ni: nilist)
            {
                ArrayList<InetAddress> ialist = Collections.list(ni.getInetAddresses());
                for (InetAddress address: ialist){
                    if (!address.isLoopbackAddress() && isIpAddressV4(address)) {
                        return address.getHostAddress();
                    }
                }

            }

        } catch (SocketException ex) {
            Log.e("localip", ex.toString());
        }
        return null;
    }

    public static String intToIp(int ipInt) {
        StringBuilder sb = new StringBuilder();
        sb.append(ipInt & 0xFF).append(".");
        sb.append((ipInt >> 8) & 0xFF).append(".");
        sb.append((ipInt >> 16) & 0xFF).append(".");
        sb.append((ipInt >> 24) & 0xFF);
        return sb.toString();
    }

    //

    /**
     * 获取网络运营商名称
     * <p>中国移动、如中国联通、中国电信</p>
     *
     * @return 运营商名称
     */
    public static String getNetworkOperatorName(Context context) {
        String opeType = null;
        // No sim
        if (!hasSim(context.getApplicationContext())) {
            return opeType;
        }

        TelephonyManager tm = (TelephonyManager) context.getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE);
        String operator = tm.getSimOperator();
        String operatorName = tm.getSimOperatorName();
        if ("46001".equals(operator) || "46006".equals(operator) || "46009".equals(operator)) {
            opeType = "中国联通";
        } else if ("46000".equals(operator) || "46002".equals(operator) || "46004".equals(operator) || "46007".equals(operator)) {
            opeType = "中国移动";

        } else if ("46003".equals(operator) || "46005".equals(operator) || "46011".equals(operator)) {
            opeType = "中国电信";
        } else {
            opeType = null;
        }
        return opeType;
    }

    /**
     * 检查手机是否有sim卡
     */
    private static boolean hasSim(Context context) {
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String operator = tm.getSimOperator();
        if (TextUtils.isEmpty(operator)) {
            return false;
        }
        return true;
    }

    /**
     * 判断数据流量开关是否打开
     *
     * @param context
     * @return
     */
    public static boolean isMobileDataEnabled(Context context) {
        try {
            Method method = ConnectivityManager.class.getDeclaredMethod("getMobileDataEnabled");
            method.setAccessible(true);
            ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            return (Boolean) method.invoke(connectivityManager);
        } catch (Throwable t) {
            return false;
        }
    }

}

